import { NextRequest, NextResponse } from 'next/server'
import { getUsers, updateUser, getUserWithStats } from '@/lib/database'
import { requireAuth, withErrorHandling } from '@/lib/auth-middleware'
import { userValidation, validateInput } from '@/lib/validation'

// 获取当前用户资料
export const GET = withErrorHandling(async (request: NextRequest) => {
  return requireAuth(request, async (req) => {
    const userId = req.user?.id

    if (!userId) {
      return NextResponse.json(
        { error: '用户ID不存在' },
        { status: 400 }
      )
    }

    // 使用包含统计信息的函数
    const user = await getUserWithStats(userId)

    if (!user) {
      return NextResponse.json(
        { error: '用户不存在' },
        { status: 404 }
      )
    }

    // 不返回敏感信息
    const { password, ...safeUser } = user

    return NextResponse.json({
      success: true,
      data: safeUser
    })
  })
})

// 更新当前用户资料
export const PUT = withErrorHandling(async (request: NextRequest) => {
  return requireAuth(request, async (req) => {
    const userId = req.user?.id

    if (!userId) {
      return NextResponse.json(
        { error: '用户ID不存在' },
        { status: 400 }
      )
    }

    const body = await request.json()
    
    // 验证输入数据
    const validation = validateInput(userValidation.updateProfile, body)
    if (!validation.success) {
      return NextResponse.json(
        { error: '输入数据无效', details: validation.errors },
        { status: 400 }
      )
    }

    const { name, email, bio, website, avatar } = validation.data

    // 检查邮箱是否已被其他用户使用
    const users = await getUsers()
    const existingUser = users.find(u => u.email === email && u.id !== userId)
    
    if (existingUser) {
      return NextResponse.json(
        { error: '该邮箱已被其他用户使用' },
        { status: 409 }
      )
    }

    // 更新用户资料
    const updatedUser = await updateUser(userId, {
      name,
      email,
      bio,
      website,
      avatar,
      updatedAt: new Date().toISOString()
    })

    if (!updatedUser) {
      return NextResponse.json(
        { error: '更新失败，用户不存在' },
        { status: 404 }
      )
    }

    // 不返回敏感信息
    const { password, ...safeUser } = updatedUser

    return NextResponse.json({
      success: true,
      data: safeUser,
      message: '资料更新成功'
    })
  })
})
